package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.CategoryException;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.pojo.Dish;
import com.itheima.reggie.pojo.DishFlavor;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {
    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorService dishFlavorService;

    public DishDto findByIdWithDishAndDishFlavor(Long id){
        DishDto dishDto = dishMapper.findByIdWithDishAndDishFlavor(id);
        return dishDto;
    }

    @Override
    public List<DishDto> selectByDto(Dish dish) {
        return dishMapper.selectByDto(dish);
    }

    @Override
    @Transactional
    public void addDishAndDishFlavor(DishDto dishDto) {
        this.save(dishDto);
        List<DishFlavor> dishFlavorList = dishDto.getFlavors();
        dishFlavorList.forEach(dishFlavor -> dishFlavor.setDishId(dishDto.getId()));
        dishFlavorService.saveBatch(dishFlavorList);
    }
    @Override
    @Transactional
    public void updateDishAndDishFlavor(DishDto dishDto) {
        this.updateById(dishDto);
        List<DishFlavor> dishFlavorList = dishDto.getFlavors();
        dishFlavorList.forEach(dishFlavor -> dishFlavor.setDishId(dishDto.getId()));
        dishFlavorService.updateBatchById(dishFlavorList);
    }

    @Override
    public Page<DishDto> findDishAndCategoryName(Page<DishDto> page1,String name) {
        return dishMapper.findDishAndCategoryName(page1,name);
    }

    @Override
    @Transactional
    public void deletByIds(Long[] ids) {
        Integer count = this.lambdaQuery()
                .in(Dish::getId, ids)
                .eq(Dish::getStatus,1)
                .count();
        if(count > 0){
            throw new CategoryException("有菜品在出售，删除失败！");
        }
        this.lambdaUpdate().in(ids!=null,Dish::getId,ids).remove();
        dishFlavorService.lambdaUpdate().in(DishFlavor::getDishId,ids).remove();

    }
}


